#!/usr/bin/python
# Robert Sigler <rsigler@gmail.com>

import crypt, getpass, pwd, random, string, sys

# Auto generate a password, or fetch one from the user
def getPass():

	# Length of auto generated password
	autoGenLength = 16

	# A list of chars to not include in autogen password
	badPasswordChars = ["'", '"', "\\", "/", "`"]
	choices = string.digits + string.letters + string.punctuation

	# Strip out "bad" chars
	for i in badPasswordChars:
		choices = string.replace(choices, i, "")

	# Auto generate a password
	autoGen = ''.join(random.choice(choices) for i in xrange(autoGenLength))

	# Show the user the auto-gen password and prompt
	print "Password not specified as param 1... here's an autogenerated " + str(autoGenLength) + " char password:"
	print autoGen
	print "Press enter to accept the autogenerated password, or enter your own when prompted"
	print

	# Get the user's input
	while True:
		passwd  = getpass.getpass("Password: ")
		# Assume the user likes the autogen password; return
		if (passwd == ""):
			return autoGen
        	passwd1 = getpass.getpass(" Confirm: ")

		# if passwords match, return. Else loop
	        if (passwd == passwd1):
			return passwd
		print "Passwords do not match, try again."

# Try to get the password from param 1
try: 
	passwd = sys.argv[1]
# if not, prompt
except:
	passwd = getPass()

# Generate a salt
salt = ''.join(random.choice(string.letters) for i in xrange(16))

# Determine the hashing algo from the script name
if "sha512" in sys.argv[0]:
	algo = "SHA512"
	hash = crypt.crypt(passwd, '$6$%s$' % salt)
elif "sha256" in sys.argv[0]:
	algo = "SHA256"
	hash = crypt.crypt(passwd, '$5$%s$' % salt)
elif "md5" in sys.argv[0]:
	algo = "MD5"
	hash = crypt.crypt(passwd, '$1$%s$' % salt)
else:
	print "Unable to determine hash type. Perhaps the script name did not include magic words to determine hashing algos."
	raise SystemExit

try:
	escHash = string.replace(string.replace(hash, "/", "\/"), "$", "\$")
	print "\n{} crypt'ed password:\n{}".format(algo, hash)
	print "\n{} crypt'ed password, escaped:\n{}".format(algo, escHash)
except:
	print sys.exc_info()
	raise SystemExit

print
